﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using BUSService;
using DTOService;

namespace QuanLyBangDia
{
    public partial class frmQuanLyBangDia : Form
    {
        #region // Các thuộc tính
        MyService myservice = new MyService();
        private int TotalRecords = 0;
        private int PageSize = 0;
        private int PageCount = 0;
        private int CurrentPage = 1;
        //Add checkbox
        bool IsHeaderCheckBoxClicked = true;
        CheckBox HeaderCheckBox;
        int TotalCheckBoxes = 0;
        int TotalCheckedCheckBoxes = 0;
        bool allowsearch = false;
        BangDia bangdia = new BangDia();
        #endregion
        
        public frmQuanLyBangDia()
        {
            InitializeComponent();
        }

        #region // Các phương thức xử lý sự kiện
        private void frmQuanLyBangDia_Load(object sender, EventArgs e)
        {
            try
            {
                //Load TenBangDia
                allowsearch = false;
                BangDia[] arrBD = myservice.SelectBangDia();
                AutoCompleteStringCollection arrCollection = new AutoCompleteStringCollection();
                foreach (BangDia bd in arrBD)
                {
                    arrCollection.Add(bd.TenBD);
                }
                txtTimTenBangDia.AutoCompleteMode = AutoCompleteMode.Suggest;
                txtTimTenBangDia.AutoCompleteSource = AutoCompleteSource.CustomSource;
                txtTimTenBangDia.AutoCompleteCustomSource = arrCollection;

                //Load LoaiSanPham                
                LoaiSanPham[] arrLSP = myservice.SelectLoaiSanPham();
                cbLoaiSanPham.DataSource = arrLSP;
                cbLoaiSanPham.DisplayMember = "TenLoaiSanPham";
                cbLoaiSanPham.ValueMember = "MaLoaiSanPham";
                cbLoaiSanPham.SelectedIndex = -1;
                LoaiSanPham[] arrLSP2 = myservice.SelectLoaiSanPham();
                cbTimLoaiSanPham.DataSource = arrLSP2;
                cbTimLoaiSanPham.DisplayMember = "TenLoaiSanPham";
                cbTimLoaiSanPham.ValueMember = "MaLoaiSanPham";
                cbTimLoaiSanPham.SelectedIndex = -1;

                //Load LoaiBangDia
                LoaiBangDia[] arrLBD = myservice.SelectLoaiBangDia();                
                cbLoaiBD.DataSource = arrLBD;
                cbLoaiBD.DisplayMember = "TenLoaiBangDia";
                cbLoaiBD.ValueMember = "MaLoaiBangDia";
                cbLoaiBD.SelectedIndex = -1;
                LoaiBangDia[] arrLBD2 = myservice.SelectLoaiBangDia();                
                cbTimLoaiBangDia.DataSource = arrLBD2;
                cbTimLoaiBangDia.DisplayMember = "TenLoaiBangDia";
                cbTimLoaiBangDia.ValueMember = "MaLoaiBangDia";
                cbTimLoaiBangDia.SelectedIndex = -1;

                //Load TinhTrang
                TinhTrang[] arrTT = myservice.SelectTinhTrang();
                cbTinhTrang.DataSource = arrTT;
                cbTinhTrang.DisplayMember = "TenTinhTrang";
                cbTinhTrang.ValueMember = "MaTinhTrang";
                cbTinhTrang.SelectedIndex = -1;
                TinhTrang[] arrTT2 = myservice.SelectTinhTrang();                
                cbTimTinhTrang.DataSource = arrTT2;
                cbTimTinhTrang.DisplayMember = "TenTinhTrang";
                cbTimTinhTrang.ValueMember = "MaTinhTrang";
                cbTimTinhTrang.SelectedIndex = -1;

                // Load BangDia
                this.PageSize = 2; //page size
                this.TotalRecords = myservice.NumberBangDia();
                this.PageCount = this.TotalRecords / this.PageSize;
                if (this.TotalRecords % this.PageSize > 0)
                    this.PageCount++;
                this.CurrentPage = 0;
                loadPage();

                //Add CheckBox Header
                TotalCheckBoxes = lvBangDia.RowCount;
                TotalCheckedCheckBoxes = 0;

                AddHeaderCheckBox();
                HeaderCheckBox.KeyUp += new KeyEventHandler(HeaderCheckBox_KeyUp);
                HeaderCheckBox.MouseClick += new MouseEventHandler(HeaderCheckBox_MouseClick);
                //End Add
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        // Add checkbok Header
        private void HeaderCheckBox_MouseClick(object sender, MouseEventArgs e)
        {
            HeaderCheckBoxClick((CheckBox)sender);
        }
        private void HeaderCheckBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
                HeaderCheckBoxClick((CheckBox)sender);
        }
        private void lvBangDia_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (!IsHeaderCheckBoxClicked)
            {
                if ((DataGridViewCheckBoxCell)lvBangDia[e.ColumnIndex, e.RowIndex] != null)
                {
                    DataGridViewCheckBoxCell RCheckBox = (DataGridViewCheckBoxCell)lvBangDia[e.ColumnIndex, e.RowIndex];
                    //Modify Counter;            
                    if ((bool)RCheckBox.Value && TotalCheckedCheckBoxes < TotalCheckBoxes)
                        TotalCheckedCheckBoxes++;
                    else if (TotalCheckedCheckBoxes > 0)
                        TotalCheckedCheckBoxes--;

                    //Change state of the header CheckBox.
                    if (TotalCheckedCheckBoxes < TotalCheckBoxes)
                        HeaderCheckBox.Checked = false;
                    else if (TotalCheckedCheckBoxes == TotalCheckBoxes)
                        HeaderCheckBox.Checked = true;
                }
            }
        }
        private void lvBangDia_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == -1 && e.ColumnIndex == 0)
                ResetLocation(e.ColumnIndex, e.RowIndex);
        }
        private void lvBangDia_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (lvBangDia.CurrentCell is DataGridViewCheckBoxCell)
                lvBangDia.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
        private void AddHeaderCheckBox()
        {
            HeaderCheckBox = new CheckBox();

            HeaderCheckBox.Size = new Size(15, 15);

            //Add the CheckBox into the DataGridView
            this.lvBangDia.Controls.Add(HeaderCheckBox);
        }
        private void ResetLocation(int ColumnIndex, int RowIndex)
        {
            //Get the column header cell bounds
            Rectangle oRectangle =
              this.lvBangDia.GetCellDisplayRectangle(ColumnIndex, RowIndex, true);

            Point oPoint = new Point();


            oPoint.X = oRectangle.Location.X + (oRectangle.Width - HeaderCheckBox.Width) / 2 + 1;
            oPoint.Y = oRectangle.Location.Y + (oRectangle.Height - HeaderCheckBox.Height) / 2 + 1;

            //Change the location of the CheckBox to make it stay on the header
            HeaderCheckBox.Location = oPoint;
        }
        private void HeaderCheckBoxClick(CheckBox HCheckBox)
        {
            IsHeaderCheckBoxClicked = true;

            foreach (DataGridViewRow Row in lvBangDia.Rows)
                ((DataGridViewCheckBoxCell)Row.Cells["Chon"]).Value = HCheckBox.Checked;

            lvBangDia.RefreshEdit();

            TotalCheckedCheckBoxes = HCheckBox.Checked ? TotalCheckBoxes : 0;

            IsHeaderCheckBoxClicked = false;
        }
        //End Add
        private void lvBangDia_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                DataGridViewRow currentRow = lvBangDia.CurrentRow;
                txtMaBD.Text = currentRow.Cells[1].Value.ToString();
                txtTenBD.Text = currentRow.Cells[2].Value.ToString();
                cbLoaiBD.Text = currentRow.Cells[3].Value.ToString();
                cbLoaiSanPham.Text = currentRow.Cells[4].Value.ToString();
                txtGiaBD.Text = currentRow.Cells[5].Value.ToString();
                txtSoLuong.Text = currentRow.Cells[6].Value.ToString();
                cbTinhTrang.Text = currentRow.Cells[7].Value.ToString();
                txtMoTa.Text = currentRow.Cells[8].Value.ToString();
            }
            catch (Exception ex)
            { }
        }

        private void btnThemBD_Click(object sender, EventArgs e)
        {
            try
            {
                lbAlert.Text = "";
                frmThemBD frm = new frmThemBD();
                DialogResult dr = frm.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    //add
                    if (allowsearch)
                        this.TotalRecords = myservice.NumberBangDia(bangdia);
                    else
                        this.TotalRecords = myservice.NumberBangDia();
                    this.PageCount = this.TotalRecords / this.PageSize;
                    if (this.TotalRecords % this.PageSize > 0)
                        this.PageCount++;
                    loadPage();
                }
            }
            catch(Exception ex)
            { throw new Exception(ex.Message); }
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            try
            {
                lbAlert.Text = "";
                String error = "";
                if (String.IsNullOrEmpty(txtMaBD.Text))
                { error += "Chọn Băng Đĩa Cần Thao Tác!\n"; }
                if (String.IsNullOrEmpty(txtTenBD.Text))
                { error += "Nhập Tên Băng Đĩa!\n"; }
                if (String.IsNullOrEmpty(cbLoaiBD.Text))
                { error += "Nhập Loại Băng Đĩa!\n"; }
                if (String.IsNullOrEmpty(txtGiaBD.Text))
                { error += "Nhập Giá Băng Đĩa!\n"; }
                if (String.IsNullOrEmpty(cbLoaiSanPham.Text))
                { error += "Nhập Loại Sản Phẩm!\n"; }
                if (String.IsNullOrEmpty(cbTinhTrang.Text))
                { error += "Nhập Tình Trạng!\n"; }
                if (String.IsNullOrEmpty(txtSoLuong.Text))
                { error += "Nhập Số Lượng!\n"; }
                if (error == "")
                {
                    BangDia bd = new BangDia();
                    bd.MaBD = txtMaBD.Text;
                    bd.TenBD = txtTenBD.Text;
                    bd.LoaiBD = int.Parse(cbLoaiBD.SelectedValue.ToString());
                    bd.LoaiSanPham = int.Parse(cbLoaiSanPham.SelectedValue.ToString());
                    bd.MoTa = txtMoTa.Text;
                    bd.SoLuong = int.Parse(txtSoLuong.Text);
                    bd.TinhTrang = int.Parse(cbTinhTrang.SelectedValue.ToString());
                    bd.GiaBD = float.Parse(txtGiaBD.Text);
                    int kq = myservice.UpdateBangDia(bd);
                    if (kq == 1)
                    {
                        MessageBox.Show("Cập nhật thành công");
                        //add
                        if (allowsearch)
                            this.TotalRecords = myservice.NumberBangDia(bangdia);
                        else
                            this.TotalRecords = myservice.NumberBangDia();                        
                        this.PageCount = this.TotalRecords / this.PageSize;
                        if (this.TotalRecords % this.PageSize > 0)
                            this.PageCount++;
                        loadPage();
                    }
                    else
                        MessageBox.Show("Cập nhật không thành công");
                }
                else
                    DevComponents.DotNetBar.MessageBoxEx.Show(error, "Thông báo", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            try
            {
                lbAlert.Text = "";
                bool flag = true;
                int k = 0;

                for (int i = 0; i < lvBangDia.Rows.Count; i++)
                {
                    if (lvBangDia.Rows[i].Cells[0].Value != null)
                    {
                        if ((bool)lvBangDia.Rows[i].Cells[0].Value == true)
                            k++;
                    }                    
                }
                if (k != 0)
                {
                    DialogResult dlKQ = MessageBox.Show("Bạn đang thao tác trên " + k.ToString() + " dòng dữ liệu?\n\nBạn có muốn xóa không ?", "Quản lý băng đĩa", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (dlKQ == DialogResult.Yes)
                    {
                        for (int i = 0; i < lvBangDia.Rows.Count; i++)
                        {
                            if (lvBangDia.Rows[i].Cells[0].Value != null)
                            {
                                if ((bool)lvBangDia.Rows[i].Cells[0].Value)
                                {
                                    DataGridViewRow dg = lvBangDia.Rows[i];
                                    if (String.IsNullOrEmpty(dg.Cells[1].Value.ToString()) == false)
                                    {
                                        int kq = myservice.DeleteBangDia(dg.Cells[1].Value.ToString());
                                        if (kq == 0)
                                        { flag = false; break; }
                                    }
                                }
                            }
                        }
                        if (flag == false) { MessageBox.Show("Xóa không thành công!"); }
                        else { lbAlert.Text = "Xóa thành công!!"; 
                          //  MessageBox.Show("Xóa thành công!"); 
                        }
                        //add                        
                        if(allowsearch)
                            this.TotalRecords = myservice.NumberBangDia(bangdia);
                        else
                            this.TotalRecords = myservice.NumberBangDia();
                        this.PageCount = this.TotalRecords / this.PageSize;
                        if (this.TotalRecords % this.PageSize > 0)
                            this.PageCount++;
                        if (this.CurrentPage == this.PageCount)
                            this.CurrentPage = this.PageCount - 1;
                        if (this.CurrentPage < 1)
                            this.CurrentPage = 0;
                        loadPage();
                    }
                }
                else
                    MessageBox.Show("Chọn dòng cần thao tác!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnTim_Click(object sender, EventArgs e)
        {
            try
            {
                allowsearch = true;
                lvBangDia.Rows.Clear();
                lbAlert.Text = "";
                bangdia = new BangDia();
                bangdia.TenBD = txtTimTenBangDia.Text;
                if (cbTimLoaiBangDia.SelectedIndex != -1)
                    bangdia.LoaiBD = int.Parse(cbTimLoaiBangDia.SelectedValue.ToString());
                if (cbTimLoaiSanPham.SelectedIndex != -1)
                    bangdia.LoaiSanPham = int.Parse(cbTimLoaiSanPham.SelectedValue.ToString());
                if (cbTimTinhTrang.SelectedIndex != -1)
                    bangdia.TinhTrang = int.Parse(cbTimTinhTrang.SelectedValue.ToString());

                this.TotalRecords = 0;
                this.PageCount = 0;
                this.CurrentPage = 1;

                this.TotalRecords = myservice.NumberBangDia(bangdia);
                this.PageCount = this.TotalRecords / this.PageSize;
                if (this.TotalRecords % this.PageSize > 0)
                    this.PageCount++;
                this.CurrentPage = 0;

                loadPage();

            }
            catch (Exception ex)
            { throw new Exception(ex.Message); }
        }

        private void btnPre_Click(object sender, EventArgs e)
        {
            try
            {
                lbAlert.Text = "";
                if (this.CurrentPage == this.PageCount)
                    this.CurrentPage = this.PageCount - 1;
                this.CurrentPage--;
                if (this.CurrentPage < 1)
                    this.CurrentPage = 0;
                loadPage();
            }
            catch
            {
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            try
            {
                lbAlert.Text = "";
                this.CurrentPage++;
                if (this.CurrentPage > (this.PageCount - 1))
                    this.CurrentPage = this.PageCount - 1;
                loadPage();
            }
            catch
            {
            }
        }

        #endregion

        #region //Các phương thức xử lý

        private void loadPage()
        {
            try
            {
                int intSkip = 0;
                intSkip = (this.CurrentPage * this.PageSize);
                BangDia[] arr = new BangDia[0];
                if (allowsearch)
                {
                    arr = myservice.TimKiemBangDia(bangdia, PageSize, intSkip);
                    if(arr.Length==0)
                        lbAlert.Text = "Kết quả không được tìm thấy!!";
                }
                else
                {
                    arr = myservice.SelectBangDia_Limit(PageSize, intSkip);
                }
                lvBangDia.Rows.Clear();
                foreach (BangDia item in arr)
                {
                    LoaiBangDia lbd = myservice.GetLoaiBangDia(item.LoaiBD);
                    LoaiSanPham lsp = myservice.GetLoaiSanPham(item.LoaiSanPham);
                    TinhTrang tt = myservice.GetTinhTrang(item.TinhTrang);
                    Object[] o = { false, item.MaBD.ToString(), item.TenBD, lbd.TenLoaiBangDia, lsp.TenLoaiSanPham, item.GiaBD, item.SoLuong.ToString(), tt.TenTinhTrang, item.MoTa };
                    lvBangDia.Rows.Add(o);
                }
                lvBangDia.Show();
                lbPage.Text = (this.CurrentPage + 1).ToString() + " / " + this.PageCount.ToString();
            }
            catch (Exception ex)
            {

            }
        }

        #endregion

       
    }
}
